<template>
  <BaseModal
    :visible="visibleModal"
    :key="id"
    width="50%"
    title="更新用户信息"
    @handleCancel="handleCancel"
    @handleOk="handleOk"
  >
    <div class="userBox">
      <div class="info">
        <div class="attrImg">
          <img :src="baseStr + detailData.userAttr" alt=""></img>
        </div>
        <div class="attrCore">
          <BaseUpload
            ref="uploadForm"
            v-model:fileList="fileList"
            listType="text"
            textFont="更新头像"
            :limit="2"
            :maxSize="1 * 1024 * 1024"
            :autoUpload="false"
            :showFileList="false"
            @change="handleChangeArrt"
          ></BaseUpload>
          <el-button @click="downloadAttr(baseStr + detailData.userAttr)"
            >下载头像</el-button
          >
        </div>

        <el-divider />
        <p><span class="p-span">ID：</span>{{ detailData.userId }}</p>
        <p><span class="p-span">等级：</span>{{ detailData.userClass }}</p>
        <p>
          <span class="p-span">签到：</span
          >{{ detailData.userSignIn ? "已签到" : "未签到" }}
        </p>
        <p class="p-spans">
          <span class="span"
            ><span class="p-span">积分：</span
            >{{ detailData.userIntegral }}</span
          >
          <span class="span"
            ><span class="p-span">收藏：</span
            >{{ detailData.userCollect.length }}</span
          >
          <span class="span"
            ><span class="p-span">分享：</span
            >{{ detailData.userShareNumber }}</span
          >
          <span class="span"
            ><span class="p-span">关注：</span
            >{{ detailData.userFocus.length }}</span
          >
        </p>
        <p>
          <span class="p-span">注册时间：</span>{{ detailData.userSignDate }}
        </p>
        <p>
          <span class="p-span">上次登录：</span
          >{{ detailData.userLastDate || "未登录过系统" }}
        </p>
      </div>
      <el-form ref="modelForm" class="modelForm" :model="detailData">
        <el-row>
          <el-col>
            <BaseInput
              label="昵称"
              v-model="detailData.userName"
              prop="userName"
              :clearable="true"
            >
            </BaseInput>
            <BaseSelect
              label="称号"
              v-model="detailData.userSalutation"
              :options="userSalutationData"
              prop="userSalutation"
              :clearable="true"
            >
            </BaseSelect>
            <BaseInput
              label="邮箱"
              v-model="detailData.userEmail"
              prop="userEmail"
              :clearable="true"
            >
            </BaseInput>

            <BaseRadioGroup
              label="账号状态"
              v-model="detailData.userAccountStatus"
              :option="userAccountStatusData"
            >
            </BaseRadioGroup>
            <BaseRadioGroup
              label="账号角色"
              v-model="detailData.userFunc"
              :option="userFuncData"
            >
            </BaseRadioGroup>
            <BaseRadioGroup
              label="账号权限"
              v-model="detailData.userAccountLimit"
              :option="userAccountLimitData()"
            >
            </BaseRadioGroup>
            <BaseTextArea label="座右铭" v-model="detailData.userDesc">
            </BaseTextArea>
            <el-form-item label="荣誉成员">
              <el-switch
                v-model="detailData.userHonor"
                active-text="荣"
                inactive-text="普"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </BaseModal>
</template>

<script setup lang="ts" name="adminUserModal">
import * as api from "@/api/index";
import {
  BaseInput,
  BaseSelect,
  BaseModal,
  BaseRadioGroup,
  BaseTextArea,
  BaseUpload,
} from "@components/BaseForm/index";
import { ref } from "vue";
import type { FormInstance } from "element-plus";
import { postAction, getAction } from "@api/request";
import { ElMessage as message } from "element-plus";
import useUserStore from "@store/userStore";
import type { UploadFile, UploadFiles, UploadInstance } from "element-plus";
import { isDisabled } from "./core";
let emit = defineEmits(["refresh"]);
let userData: any = useUserStore().userInfo;
let fileList = ref<UploadFiles>([]);
// form表单实例
let modelForm = ref<FormInstance>();
let baseStr: string = import.meta.env.config_concat;
// 需要提交的数据
let detailData = ref({
  userAccountStatus: "",
  userSalutation: "",
  userSalutationList: [],
  userName: "",
  userAccountLimit: 0,
  userFunc: 0,
  userEmail: "",
  userHonor: 0,
  userDesc: "",
  userSignDate: "",
  userLastDate: "",
  userAttr: "",
  userId: "",
  userClass: 1,
  userSignIn: false,
  userIntegral: 0,
  userCollect: [],
  userShareNumber: 0,
  userFocus: [],
});

// 账号状态数据
let userAccountStatusData = [
  {
    label: "正常",
    coreVal: 0,
    disabled: false,
  },
  {
    label: "冻结",
    coreVal: 1,
    disabled: false,
  },
  {
    label: "异常",
    coreVal: 2,
    disabled: false,
  },
  {
    label: "封停",
    coreVal: 3,
    disabled: false,
  },
];
// 账号权限数据
let userAccountLimitData = () => [
  {
    label: "普通用户",
    coreVal: 0,
    disabled: isDisabled(detailData.value.userId, userData),
  },
  {
    label: "管理员",
    coreVal: 1,
    disabled: isDisabled(detailData.value.userId, userData),
  },
  {
    label: "超级管理员",
    coreVal: 2,
    disabled: true,
  },
];
// 账号角色数据
let userFuncData = [
  {
    label: "用户",
    coreVal: 0,
    disabled: false,
  },
  {
    label: "前端开发",
    coreVal: 1,
    disabled: false,
  },
  {
    label: "后端开发",
    coreVal: 2,
    disabled: false,
  },
  {
    label: "全栈开发",
    coreVal: 3,
    disabled: false,
  },
];
// 用户称号数据
let userSalutationData: any = ref([]);
let userSalutationDataFn = () => {
  userSalutationData.value.splice(0, userSalutationData.value.length);
  detailData.value.userSalutationList.forEach((item: any) => {
    userSalutationData.value.push([item.name, item.name]);
  });
};
// 相关url
let pageUrl = {
  edit: api.admin.URL_USERUPDATE,
};

let visibleModal = ref(false);

let id = ref("");

let handleShow = (val: boolean, item: objectType<any>) => {
  console.log(val, item, 121233);
  id.value = item?.userId || "";
  visibleModal.value = val;
  if (id.value) {
    getDetail();
  } else {
    message.warning("缺少用户id参数");
  }
};

let handleChangeArrt = (file: any, fileLists: any) => {
  for (let i = 0; i < fileList.value.length; i++) {
    let formData = new FormData();
    let file: any = fileList.value[i].raw;
    formData.append("file", file);
    formData.append("attr", `${i}`);
    formData.append("originMode", import.meta.env.config_mode);
    api.upload
      .userUploadAttr(formData, { neverCancel: true })
      .then((res: any) => {
        if (res.header.code === 999) {
          fileList.value[i].status = "success";
          message.success(res.header.message || "图片已上传");
        }
      });
  }
};

let handleCancel = () => {
  visibleModal.value = false;
};

let handleOk = () => {
  postAction(pageUrl.edit, detailData.value).then((res) => {
    if (res.header.code === 999) {
      emit("refresh");
      handleCancel();
      message.success(res.header.message || "用户信息已更新");
      return;
    }
  });
};

// 下载头像
let downloadAttr = (url: string) => {
  postAction(url).then((res) => {
    if (res.header.code === 999) {
      let tag = document.createElement("a");
      tag.style.display = "none";
      tag.href = res.body.data;
      tag.download = res.body.fileName;
      document.querySelectorAll("body")[0].appendChild(tag);
      tag.click();
      tag.remove();
    }
  });
};

// 获取详情
let getDetail = () => {
  if (id.value) {
    // 编辑 or 详情
    api.admin
      .userDetail({ userId: id.value })
      .then((res: BaseResponse<BaseListType>) => {
        if (res.header.code === 999) {
          fixednessOrigin(detailData.value, { ...res.body });
          userSalutationDataFn();
        }
      });
  }
};

// 不破坏原对象 保证其响应式
let fixednessOrigin = (
  originObj: objectType<any>,
  dataObj: objectType<any>
) => {
  let dataArr = Object.entries(dataObj);
  dataArr.forEach((item) => {
    originObj[item[0]] = item[1];
  });
};

defineExpose({
  handleShow,
});
</script>

<style lang="less" scoped>
:deep(.el-radio.el-radio--large) {
  height: 32px;
}
.userBox {
  display: flex;
  .info {
    flex: 4;
    .attrImg {
      width: 50%;
      border-radius: 50%;
      transform: translateX(28%);
      overflow: hidden;
      position: relative;
      img {
        width: 100%;
      }
      .upload {
        position: absolute;
        bottom: 0px;
        right: 0px;
        font-size: 24px;
      }
    }
    .attrCore {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
      padding-right: 20%;
    }
    p {
      line-height: 32px;
      .p-span {
        font-weight: 700;
      }
    }
    .p-spans {
      display: flex;

      .span {
        flex: 1;
      }
    }
  }
  .modelForm {
    flex: 6;
  }
}
</style>
